import 'dart:math';

import 'package:ac/common/ac_pv_manager.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/model/ac_blogger_model.dart';
import 'package:ac/model/ac_login_model.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

import 'ac_post_list_state.dart';

class AcPostListLogic extends GetxController {
  final AcPostListState state = AcPostListState();
  final bloggerList = <AcBloggerModel>[].obs;
  final postList = <Post>[].obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    state.index.value = Get.arguments;
    _initData();
    LogPvManger.stat(page: LogPages.postListPage);
  }

  void _initData() {
    int n = 6; // 选择的项数
    bloggerList.value =
        _getRandomItems<AcBloggerModel>(AcUserManager.bloggerList, n);
    for (var value in bloggerList) {
      if(value.userInfo?.isBlock != true){
        postList.addAll(value.post);
      }else{
        debugPrint('block user');
      }
    }
    postList.shuffle();
  }

  List<T> _getRandomItems<T>(List<T> list, int n) {
    if (n > list.length) {
      throw ArgumentError('n 不能大于列表的长度');
    }

    Random random = Random();
    List<T> copyList = List.from(list); // 创建列表副本，以免修改原始列表

    List<T> resultList = [];
    for (int i = 0; i < n; i++) {
      int randomIndex = random.nextInt(copyList.length);
      resultList.add(copyList[randomIndex]);
      copyList.removeAt(randomIndex); // 从副本中移除已选择的项，避免重复选择
    }

    return resultList;
  }

  Userinfo? findBlogger(Post post) {
    for (var value in bloggerList) {
      if (value.post.contains(post)) {
        return value.userInfo;
      }
    }
    return null;
  }

  void refreshUserInfo() {
    postList.clear();
    for (var value in bloggerList) {
      value.userInfo = AcUserManager.getUserInfo(value.userInfo!.userId!);
      if(value.userInfo?.isBlock != true){
        postList.addAll(value.post);
      }
    }
    postList.refresh();
  }
}
